package com.huawei.demo;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.das.v3.DasClient;
import com.huaweicloud.sdk.das.v3.model.ListDbUsersRequest;
import com.huaweicloud.sdk.das.v3.model.ListDbUsersResponse;
import com.huaweicloud.sdk.das.v3.model.ShowDbUserRequest;
import com.huaweicloud.sdk.das.v3.model.ShowDbUserResponse;
import com.huaweicloud.sdk.das.v3.region.DasRegion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DataBaseUserInfoDemo {
    private static final Logger logger = LoggerFactory.getLogger(DataBaseUserInfoDemo.class.getName());

    /**
     * args[0] = <<YOUR AK>>
     * args[1] = <<YOUR SK>>
     * args[2] = <<YOUR REGION_ID>>
     * args[3] = <<YOUR INSTANCE_ID>>
     * args[4] = <<YOUR USER_ID>>
     */
    public static void main(String[] args) {
        String ak = args[0];
        String sk = args[1];
        String regionId = args[2];
        String instanceId = args[3];
        String userId = args[4];

        ICredential auth = new BasicCredentials()
                .withAk(ak)
                .withSk(sk);
        DasClient client = DasClient.newBuilder()
                .withCredential(auth)
                .withRegion(DasRegion.valueOf(regionId))
                .build();

        // 查询数据库用户列表
        listDbUsers(client, instanceId);

        // 查询数据库用户信息
        showDbUser(client, instanceId, userId);
    }

    private static void listDbUsers(DasClient client, String instanceId) {
        ListDbUsersRequest request = new ListDbUsersRequest();
        request.withInstanceId(instanceId);

        invokeClient(() -> {
            ListDbUsersResponse response = client.listDbUsers(request);
            logger.info(response.toString());
        });
    }

    private static void showDbUser(DasClient client, String instanceId, String userId) {
        ShowDbUserRequest request = new ShowDbUserRequest();
        request.withInstanceId(instanceId);
        request.withDbUserId(userId);

        invokeClient(() -> {
            ShowDbUserResponse response = client.showDbUser(request);
            logger.info(response.toString());
        });
    }

    private static <T> void invokeClient(Runnable runnable) {
        try {
            runnable.run();
        } catch (ConnectionException e) {
            logger.error("ConnectionException", e);
        } catch (RequestTimeoutException e) {
            logger.error("RequestTimeoutException", e);
        } catch (ServiceResponseException e) {
            logger.error("httpStatusCode: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(), e.getErrorCode(),
                    e.getErrorMsg());
        }
    }
}
